<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-11-23 13:56:12
 * @Last Modified time: 2022-12-07 19:23:39
 */

namespace app\sys\controller\system;
use app\sys\controller\Base;
use think\facade\{
    App
};
use frank\services\NodeService;
use app\common\services\system\AddonService;

/**
 * 插件管理
 * Class Addon 
 * @package app\sys\controller\system
 */
class Addon extends Base
{
    /**
     * Role constructor.
     * @param App $app
     * @param AddonService $service
     */
    public function __construct(App $app, AddonService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 插件列表
     * @method(GET)
     */
    public function list()
    {
        $data = $this->request->getMore([
        ]);
        $this->success($this->service->getPageList($data));
    }

    /**
     * 插件详细 
     * @noAuth(true)
     * @method(GET)
     */
    public function detail(){
        $this->success($this->service->getDetail($this->request->get('id')));
    }

    /**
     * 添加插件
     * @method(POST)
     */
    public function store(){
        $data = $this->request->getMore([
            ['title', ''],
            ['addon_name', ''],
            ['desc', ''],
            ['icon', ''],
            ['version', ''],
        ]);
        if (!$data['title'])
            $this->error('请输入插件名称');
        if (!$data['addon_name'])
            $this->error('请输入插件标识');
        $addon = $this->service->getOne(['addon_name' => $data['addon_name']]);
        if ($addon) {
        	$this->error('该插件标识已存在！请重新输入');
        }
        if ($this->service->save($data)){
            $this->success('保存成功');
        }
        $this->error('保存失败');
    }

    /**
     * 编辑插件
     * @method(PUT)
     */
    public function update()
    {
        if (!$id = $this->request->param('id')) {
            $this->error('参数错误!');
        }
        $data = $this->request->postMore([
            ['title', ''],
            ['addon_name', ''],
            ['desc', ''],
            ['icon', ''],
            ['version', ''],
        ]);
        if (!$data['title'])
            $this->error('请输入插件名称');
        if (!$data['addon_name'])
            $this->error('请输入插件标识');
        $addon = $this->service->getOne(['addon_name' => $data['addon_name']]);
        if ($addon && $addon['id'] != $id) {
        	$this->error('该插件标识已存在！请重新输入');
        }
        if($this->service->update($id, $data)){
            $this->success('修改成功!');
        }
        $this->error('修改失败!');
    }

    /**
     * 删除插件
     * @method(DELETE)
     */
    public function delete()
    {
        if (!$id = $this->request->param('id')) {
            $this->error('参数错误!');
        }

        if ($this->service->delete((int)$id)) {
            $this->success('删除成功!');
        } 
        $this->error('删除失败!');
    }
}